package com.pft.web.view.presenter;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.gprinter.command.EscCommand;
import com.pft.web.App;
import com.pft.web.R;
import com.pft.web.manager.DeviceConnFactoryManager;
import com.pft.web.manager.PrinterCommand;
import com.pft.web.manager.ThreadPool;
import com.pft.web.model.constants.Constant;
import com.pft.web.model.entities.PrintData;
import com.pft.web.util.Utils;
import com.pft.web.view.contract.BlueToothContract;

import java.util.List;
import java.util.Vector;

public class BlueToothPresenter implements BlueToothContract.Presenter {


    BlueToothContract.View mView;

    /**
     * 连接状态断开
     */
    private static final int CONN_STATE_DISCONN = 0x007;
    /**
     * 使用打印机指令错误
     */
    private static final int PRINTER_COMMAND_ERROR = 0x008;

    private static final int CONN_MOST_DEVICES = 0x11;
    private static final int CONN_PRINTER = 0x12;

    ThreadPool threadPool;
    int id = 0;

    public BlueToothPresenter(BlueToothContract.View view) {
        this.mView = view;
    }


    private EscCommand.JUSTIFICATION parseJust(int just) {
        if (just == 2) {
            return EscCommand.JUSTIFICATION.RIGHT;
        } else if (just == 1) {
            return EscCommand.JUSTIFICATION.CENTER;
        } else {
            return EscCommand.JUSTIFICATION.LEFT;
        }
    }

    /**
     * 发送票据
     */
    void sendReceiptWithResponse(List<PrintData> printDatas) {
        EscCommand esc = new EscCommand();
        esc.addInitializePrinter();
        esc.addPrintAndFeedLines((byte) 3);

        for (PrintData printData : printDatas) {
            esc.addSelectJustification(parseJust(printData.just));

            if (printData.isBig) {
                esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);
                esc.addSetQuadrupleModeForKanji(EscCommand.ENABLE.ON);
            } else {
                esc.addSetQuadrupleModeForKanji(EscCommand.ENABLE.OFF);
                esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);
            }
            switch (printData.type) {
                case 0:

                    List<PrintData> child = printData.printData;
                    if (child != null) {
                        esc.addSetHorAndVerMotionUnits((byte) 7, (byte) 0);
                        short padding = 0;
                        for (PrintData data : child) {
                            if (printData.isBig) {
                                esc.addSelectPrintModes(EscCommand.FONT.FONTB, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);
                            } else {
                                esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);
                            }
                            esc.addSetAbsolutePrintPosition(padding);
                            padding += 6;
                            esc.addText(data.content);
                        }
                    } else {
                        esc.addText(printData.content);
                    }
                    break;

                case 1:
                    esc.addSelectErrorCorrectionLevelForQRCode((byte) 0x31);
                    // 设置qrcode模块大小
                    esc.addSelectSizeOfModuleForQRCode((byte) 6);
                    // 设置qrcode内容
                    esc.addStoreQRCodeData(printData.content);
                    esc.addPrintQRCode();// 打印QRCode
                    break;
            }
            esc.addPrintAndLineFeed();
        }

        esc.addPrintAndLineFeed();


        Vector<Byte> datas = esc.getCommand();
        // 发送数据
        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(datas);
    }

//
//    /**
//     * 发送票据
//     */
//    void sendReceiptWithResponse() {
//        EscCommand esc = new EscCommand();
//        esc.addInitializePrinter();
//        esc.addPrintAndFeedLines((byte) 3);
//        // 设置打印居中
//        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
//        // 设置为倍高倍宽
//        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);
//        // 打印文字
//        esc.addText("Sample\n");
//        esc.addPrintAndLineFeed();
//
//        /* 打印文字 */
//        // 取消倍高倍宽
//        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);
//        // 设置打印左对齐
//        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
//        // 打印文字
//        esc.addText("Print text\n");
//        // 打印文字
//        esc.addText("Welcome to use SMARNET printer!\n");
//
//        /* 打印繁体中文 需要打印机支持繁体字库 */
//        String message = "佳博智匯票據打印機\n";
//        esc.addText(message, "GB2312");
//        esc.addPrintAndLineFeed();
//
//        /* 绝对位置 具体详细信息请查看GP58编程手册 */
//          esc.addText("智汇");
//        esc.addSetHorAndVerMotionUnits((byte) 7, (byte) 0);
//        esc.addSetAbsolutePrintPosition((short) 6);
//        esc.addText("网络");
//        esc.addSetAbsolutePrintPosition((short) 10);
//        esc.addText("设备");
//        esc.addPrintAndLineFeed()
//
//        /* 打印图片 */
//        // 打印文字
//        esc.addText("Print bitmap!\n");
//        Bitmap b = BitmapFactory.decodeResource(App.getContext().getResources(),
//                R.mipmap.ic_launcher);
//        // 打印图片
//        esc.addOriginRastBitImage(b, 384, 0);
//
//        /* 打印一维条码 */
//        // 打印文字
//        esc.addText("Print code128\n");
//        esc.addSelectPrintingPositionForHRICharacters(EscCommand.HRI_POSITION.BELOW);
//        // 设置条码可识别字符位置在条码下方
//        // 设置条码高度为60点
//        esc.addSetBarcodeHeight((byte) 60);
//        // 设置条码单元宽度为1
//        esc.addSetBarcodeWidth((byte) 1);
//        // 打印Code128码
//        esc.addCODE128(esc.genCodeB("SMARNET"));
//        esc.addPrintAndLineFeed();
//
//        /*
//         * QRCode命令打印 此命令只在支持QRCode命令打印的机型才能使用。 在不支持二维码指令打印的机型上，则需要发送二维条码图片
//         */
//        // 打印文字
//        esc.addText("Print QRcode\n");
//        // 设置纠错等级
//        esc.addSelectErrorCorrectionLevelForQRCode((byte) 0x31);
//        // 设置qrcode模块大小
//        esc.addSelectSizeOfModuleForQRCode((byte) 3);
//        // 设置qrcode内容
//        esc.addStoreQRCodeData("www.smarnet.cc");
//        esc.addPrintQRCode();// 打印QRCode
//        esc.addPrintAndLineFeed();
//
//        // 设置打印左对齐
//        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
//        //打印文字
//        esc.addText("Completed!\r\n");
//
//        // 开钱箱
//        esc.addGeneratePlus(LabelCommand.FOOT.F5, (byte) 255, (byte) 255);
//        esc.addPrintAndFeedLines((byte) 8);
//        // 加入查询打印机状态，打印完成后，此时会接收到GpCom.ACTION_DEVICE_STATUS广播
//        esc.addQueryPrinterStatus();
//        Vector<Byte> datas = esc.getCommand();
//        // 发送数据
//        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(datas);
//    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.CONN_STATE_DISCONN:
                    if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null) {
                        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
                    }
                    break;
                case PRINTER_COMMAND_ERROR:
                    Utils.toast(App.getContext(), App.getContext().getResources().getString(R.string.str_choice_printer_command));
                    break;
                case CONN_PRINTER:
                    Utils.toast(App.getContext(), App.getContext().getResources().getString(R.string.str_cann_printer));
                    break;
                case Constant.MESSAGE_UPDATE_PARAMETER:
                    String strIp = msg.getData().getString("Ip");
                    String strPort = msg.getData().getString("Port");
                    //初始化端口信息
                    new DeviceConnFactoryManager.Build()
                            //设置端口连接方式
                            .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.WIFI)
                            //设置端口IP地址
                            .setIp(strIp)
                            //设置端口ID（主要用于连接多设备）
                            .setId(id)
                            //设置连接的热点端口号
                            .setPort(Integer.parseInt(strPort))
                            .build();
                    threadPool = ThreadPool.getInstantiation();
                    threadPool.addTask(new Runnable() {
                        @Override
                        public void run() {
                            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort();
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    };


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {

                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                    mHandler.obtainMessage(CONN_STATE_DISCONN).sendToTarget();
                    break;
                case DeviceConnFactoryManager.ACTION_CONN_STATE:
                    int state = intent.getIntExtra(DeviceConnFactoryManager.STATE, -1);
                    int deviceId = intent.getIntExtra(DeviceConnFactoryManager.DEVICE_ID, -1);
                    switch (state) {
                        case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:
                            if (id == deviceId) {
                                Utils.toast(App.getContext(), App.getContext().getResources().getString(R.string.str_conn_state_disconnect));

                            }
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTING:
                            Utils.toast(App.getContext(), App.getContext().getResources().getString(R.string.str_conn_state_connecting));
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                            Utils.toast(App.getContext(), "连接成功");
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_FAILED:
                            Utils.toast(App.getContext(), App.getContext().getResources().getString(R.string.str_conn_fail));
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public BroadcastReceiver getReceiver() {
        return receiver;
    }

    @Override
    public void receiptPrint(final List<PrintData> printData) {
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null ||
                !DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getConnState()) {
            Utils.toast(App.getContext(), App.getContext().getResources().getString(R.string.str_cann_printer));
            return;
        }
        threadPool = ThreadPool.getInstantiation();
        threadPool.addTask(new Runnable() {
            @Override
            public void run() {

//                for (PrintData printDatum : printData) {
//                    if (printDatum.type == 1) {
//                        try {
//
//                            String dd = printDatum.content;
//                            Log.e("lishm",dd);
//                            Bitmap bitmap = Glide.with(mView.getActivity())
//                                    .load(dd)
//                                    .asBitmap()
//                                    .diskCacheStrategy(DiskCacheStrategy.NONE)
//                                    .into(221, 221)
//                                    .get();
//                            printDatum.bitmap = bitmap;
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        } catch (ExecutionException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }


                if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getCurrentPrinterCommand() == PrinterCommand.ESC) {
                    sendReceiptWithResponse(printData);
                } else {
                    mHandler.obtainMessage(PRINTER_COMMAND_ERROR).sendToTarget();
                }
            }
        });
    }
}
